<?php

/**
 * This is the model class for table "{{hierarchy}}".
 *
 * The followings are the available columns in table '{{hierarchy}}':
 * @property integer $id
 * @property integer $sort
 * @property integer $parent
 * @property string $title
 * @property string $router
 * @property string $url
 */
class Hierarchy extends CActiveRecord
{
    /**
     * @var $childs Array
     */
    private $childs;
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Hierarchy the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{hierarchy}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('title,sort,parent', 'required'),
			array('sort, parent,is_backend', 'numerical', 'integerOnly'=>true),
			array('title,router,url', 'length', 'max'=>255),
            array('url','url'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, sort, parent, title', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
            'getparent' => array(self::BELONGS_TO, 'Hierarchy', 'parent'),
            'childs' => array(self::HAS_MANY, 'Hierarchy', 'parent', 'order' => 'sort ASC'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'sort' => 'Vị trí',
			'parent' => 'Cấp cha',
			'title' => 'Tên menu',
			'url' => 'Đường dẫn (Link)',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('sort',$this->sort);
		$criteria->compare('parent',$this->parent);
		$criteria->compare('title',$this->title,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

    public function getListed() {
        $this->_getChilds();
        $subitems = array();
        if($this->childs){
            foreach($this->childs as $child) {
                /**
                 * @var $child Hierarchy
                 */
                $subitems[] = $child->getListed();
            }
        }

        if($this->router){
            $url = Yii::app()->createUrl($this->router);
        }elseif($this->url){
            $url = $this->url;
        }

        $returnarray = array();
        if(isset($url) && $url){
            $returnarray['label'] = $this->title;
            $returnarray['url'] = $url;
        }else{
            $returnarray['label'] = $this->title;
        }

        if($this->is_backend){
            $returnarray['visible'] = !Yii::app()->user->isGuest && Yii::app()->user->checkAccess("admin");
        }

        if($subitems != array()){
            $returnarray = array_merge($returnarray, array('items' => $subitems));
        }
        return $returnarray;
    }

    public function getOptions() {
        $this->_getChilds();
        $subitems = array();
        if($this->childs) foreach($this->childs as $child) {
            /**
             * @var $child Hierarchy
             */
            $subitems[] = $child->getOptions();
        }
        $returnarray = array($this->id => $this->title);
        if($subitems != array())
        {
            $returnarray = array_merge($returnarray, $subitems);
        }

        return $returnarray;
    }

    public function htmlOptionData(){
        $data = $this->findAll();
        $items = array(0=>'--None--');
        if($data){
            foreach($data as $pitem){
                $items[$pitem->id] = $pitem->title;
            }
        }
        return $items;
    }
    private function _getChilds(){
        if(!$this->isNewRecord){
            $criteria = new CDbCriteria(array('condition'=>'parent = '.$this->id,'order'=>'sort ASC'));
            $this->childs = $this->findAll($criteria);
        }

    }
}